<template>
  <el-row>
    <el-col>
      <el-card>
        <!--搜索框开始-->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-button type="success" style="margin-bottom: 10px;" @click="showAddModel">新增</el-button>
          </el-col>
          <el-col :span="16">
            <div class="m-4">
              <div class="block" style="float: right; margin-right: 10px;">
                <el-select
                    v-model="condition.status"
                    placeholder="请选择是否上架"
                    clearable
                    :value-on-clear=null
                    style="width: 150px"
                    @change="selectByPage(1)"
                >
                  <el-option   label="上架" value="1" />
                  <el-option  label="下架" value="0" />
                </el-select>
              </div>
              <div class="block" style="float: right; margin-right: 10px;">
                <el-cascader
                    placeholder="请选择分类"
                    v-model="condition.categoryId"
                    :options="allParent"
                    :props="props"
                    clearable
                    :value-on-clear=null
                    @change="selectByPage(1)"
                    style="width: 150px"
                />
              </div>
              <div class="block" style="float: right; margin-right: 10px;">
                <el-input
                    v-model="condition.name"
                    placeholder="请选择商品名称"
                    clearable
                    @change="selectByPage(1)"
                    style="width: 150px"
                />
              </div>
            </div>
          </el-col>
        </el-row>
        <!--搜索框结束-->
        <!--表格开始-->
        <el-table :data="pageInfo.list" border style="width: 100%;">
          <el-table-column prop="id" label="ID" :width="50" />
          <el-table-column prop="dscp" label="描述" />
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="price" label="售价" />
          <el-table-column prop="markPrice" label="标价" />
          <el-table-column prop="purchasePrice" label="进价" />
          <el-table-column prop="color" label="颜色" />
          <el-table-column prop="version" label="版本" />
          <el-table-column prop="count" label="数量" width="60px" />
          <el-table-column label="分类">
            <template #default="scope">
              <el-text class="mx-1" type="primary">
                {{scope.row.category.name}}
              </el-text>
            </template>
          </el-table-column>
          <el-table-column prop="recom" label="是否推荐">
            <template #default="scope">
              <el-switch v-model="scope.row.recom"
                         inline-prompt
                         :inactive-value="0"
                         :active-value="1"
                         style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                         inactive-text="不推荐"
                         active-text="推荐"
                         @change="changeRecom(scope.row.id, scope.row.recom)"
              >

              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="是否上架">
            <template #default="scope">
              <el-switch v-model="scope.row.status"
                         inline-prompt
                         :inactive-value="0"
                         :active-value="1"
                         style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                         inactive-text="下架"
                         active-text="上架"
                         @change="chgStatus(scope.row.id, scope.row.status)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="评分" width="60px"/>
          <el-table-column label="图片" width="110px">
            <template #default="scope">

              <el-popover placement="right" trigger="hover" v-if="scope.row.picList.length > 0">
                <template #reference>
                  <el-image style="width: 80px; height: 80px" :src="SERVER_ADDR + '/goods/pic/' + scope.row.picList[0].url" />
                </template>
                <el-image v-for="(pic, index) in scope.row.picList" :key="index" style="width: 50px; height: 50px; margin-left: 5px" :src="SERVER_ADDR + '/goods/pic/' + pic.url" />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="227">
            <template #default="scope">
              <el-button type="success" style="margin-bottom: 10px" @click="showDetailModel(scope.row)"> 详情</el-button>
              <el-button type="primary" style="margin-bottom: 10px" @click="showUpdateModel(scope.row.id)"> 修改</el-button>
              <el-popconfirm
                  title="你确定删除吗？"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="deleteGoods(scope.row.id)"
              >
                <template #reference>
                  <el-button style="margin-bottom: 10px;" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--表格结束-->
        <!-- 分页开始 -->
        <el-row class="row-bg" justify="center">
          <el-pagination background layout="prev, pager, next"
                         :page-count="pageInfo.pages"
                         @update:current-page="selectByPage"
                         style="margin-top: 10px;"
                         v-model:current-page="pageInfo.pageNum" />
        </el-row>
        <!-- 分页结束 -->
      </el-card>
    </el-col>
  </el-row>
  <!-- 新增商品对话框开始 -->
  <el-dialog v-model="addDislogShow" title="新增商品" width="500">
    <el-form>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="goodsAdd.name" autocomplete="off" placeholder="请输入名称" style="width: 240px" />
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="goodsAdd.dscp" autocomplete="off" placeholder="请输入描述" style="width: 240px" />
      </el-form-item>
      <el-form-item label="售价" label-width="20%">
        <el-input v-model="goodsAdd.price" autocomplete="off" placeholder="请输入售价" style="width: 240px" />
      </el-form-item>
      <el-form-item label="标价" label-width="20%">
        <el-input v-model="goodsAdd.markPrice" autocomplete="off" placeholder="请输入标价" style="width: 240px" />
      </el-form-item>
      <el-form-item label="进价" label-width="20%">
        <el-input v-model="goodsAdd.purchasePrice" autocomplete="off" placeholder="请输入进价" style="width: 240px" />
      </el-form-item>
      <el-form-item label="颜色" label-width="20%">
        <el-input v-model="goodsAdd.color" autocomplete="off" placeholder="请输入颜色" style="width: 240px" />
      </el-form-item>
      <el-form-item label="版本" label-width="20%">
        <el-input v-model="goodsAdd.version" autocomplete="off" placeholder="请输入版本" style="width: 240px" />
      </el-form-item>
      <el-form-item label="库存" label-width="20%">
        <el-input v-model="goodsAdd.count" autocomplete="off" placeholder="请输入库存" style="width: 240px" />
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="goodsAdd.recom">
          <el-radio label="推荐" value="0" size="large"/>
          <el-radio label="不推荐" value="1" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="goodsAdd.status">
          <el-radio label="下架" value="0" size="large"/>
          <el-radio label="上架" value="1" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择类型" label-width="20%">
        <el-cascader
            placeholder="请选择分类"
            v-model="goodsAdd.categoryId"
            :options="allParent"
            :props="props"
            clearable
            :empty-values="[0]"
            :value-on-clear="0"
            @change="selectByPage(1)"
        />
      </el-form-item>
      <el-form-item label="图片" label-width="20%">
        <el-upload v-model:file-list="goodsAdd.picList"
                   :action="SERVER_ADDR + '/goods/upload'"
                   list-type="picture-card"
                   name="pic"
                   :headers="headers"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload"
                    >
          <el-icon >
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDislogShow = false">取消</el-button>
        <el-button type="primary" @click="insert">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增商品对话框结束 -->
  <!-- 修改商品对话框开始 -->
  <el-dialog v-model="updateDislogShow" title="修改商品" width="500">
    <el-form>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="goodsUpdate.name" autocomplete="off" placeholder="请输入名称" style="width: 240px" />
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="goodsUpdate.dscp" autocomplete="off" placeholder="请输入描述" style="width: 240px" />
      </el-form-item>
      <el-form-item label="售价" label-width="20%">
        <el-input v-model="goodsUpdate.price" autocomplete="off" placeholder="请输入售价" style="width: 240px" />
      </el-form-item>
      <el-form-item label="标价" label-width="20%">
        <el-input v-model="goodsUpdate.markPrice" autocomplete="off" placeholder="请输入标价" style="width: 240px" />
      </el-form-item>
      <el-form-item label="进价" label-width="20%">
        <el-input v-model="goodsUpdate.purchasePrice" autocomplete="off" placeholder="请输入进价" style="width: 240px" />
      </el-form-item>
      <el-form-item label="颜色" label-width="20%">
        <el-input v-model="goodsUpdate.color" autocomplete="off" placeholder="请输入颜色" style="width: 240px" />
      </el-form-item>
      <el-form-item label="版本" label-width="20%">
        <el-input v-model="goodsUpdate.version" autocomplete="off" placeholder="请输入版本" style="width: 240px" />
      </el-form-item>
      <el-form-item label="库存" label-width="20%">
        <el-input v-model="goodsUpdate.count" autocomplete="off" placeholder="请输入库存" style="width: 240px" />
      </el-form-item>
      <el-form-item label="选择类型" label-width="20%">
        <el-cascader
            placeholder="请选择分类"
            v-model="goodsUpdate.categoryId"
            :options="allParent"
            :props="props"
            clearable
            :empty-values="[0]"
            :value-on-clear="0"
            @change="selectByPage(1)"
        />
      </el-form-item>
      <el-form-item label="图片" label-width="20%">
        <el-upload v-model:file-list="goodsUpdate.picList"
                   :action="SERVER_ADDR + '/goods/upload'"
                   list-type="picture-card"
                   name="pic"
                   :headers="headers"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload"
        >
          <el-icon >
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDislogShow = false">取消</el-button>
        <el-button type="primary" @click="update">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改商品对话框结束 -->
  <!-- 商品详情对话框开始 -->
  <el-dialog v-model="detailDislogShow" title="商品详情">
    <template #footer>
        <div  v-if="detailDislogShow" style="border: 1px solid #ccc; margin-bottom: 5px;">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
          />
          <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="goodsUpdate.detail"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
          />
        </div>
        <el-button @click="detailDislogShow = false">取消</el-button>
        <el-button type="primary" @click="updateDetail">
          确定
        </el-button>
    </template>
  </el-dialog>
  <!-- 商品详情对话框结束 -->
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {ref,onBeforeUnmount, shallowRef, computed} from "vue";
import {ElMessage} from "element-plus";
import goodsApi from "@/api/goodsApi.js";
import categoryApi from "@/api/categoryApi.js";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import {useTokenStore} from "@/stores/tokenStore.js";

const tokenStore = useTokenStore();
const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return{
    token: token
  }
})
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
//修改详情开始
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 设置wangEditor的内容
const mode = ref('default');
//工具栏的设置
const toolbarConfig = {}
//对话框的配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage:{
      server: `${SERVER_ADDR.value}/goods/upload`,
      fieldName: "pic",
      headers: {
        token: tokenStore.tokenStr
      },
      customInsert(resp, insertFn) {                  // JS 语法
        // res 即服务端的返回结果
        let url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
        //url - 图片通过后台访问的地址
        insertFn(url);
      },
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
//是否显示详情对话框
const showDetailModel =(detail) => {
  goodsUpdate.value.id = detail.id;
  goodsUpdate.value.detail = detail.detail;
  detailDislogShow.value = true;
}
//修改推荐
const changeRecom = (id, recom) =>{
    const goods = {
      id: id,
      recom: recom
    }

    goodsApi.update(goods)
        .then(resp => {
          if (resp.code == 10000) {
            ElMessage.success(resp.msg);
            selectByPage(pageInfo.value.pageNum)
          }else{
            ElMessage.error(resp.msg);
          }
        })
}
//修改上下架
const chgStatus = (id, status) => {
  const goods = {
    id: id,
    status: status
  }

  goodsApi.update(goods)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum)
        }else{
          ElMessage.error(resp.msg);
        }
      })
}
//修改详情信息
const updateDetail = ()=>{
  console.log(goodsUpdate.value)
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000){
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum)
          detailDislogShow.value=false;
          goodsUpdate.value = {
            id: 0,
            name: "",
            dscp: "",
            detail: "",
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: "",
            version: "",
            count: null,
            recom: null,
            categoryId: null,
            status: null,
            picList:[]
          }
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
//修改详情结束
//搜索条件
const condition = ref({
  name: null,
  categoryId: null, //子分类id
  status: null
});
//分页的信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
// 请求所有的数据
const selectByPage = (PageNum) => {
  goodsApi.selectByPage(condition.value, PageNum, 10)
      .then(resp => {
        pageInfo.value =resp.data
      })
}
//级联选择器的配置选择
const props = ref({
  label: "name",
  value: "id",
  children: "childList",
  emitPath: false
})
//父分类
const allParent = ref([]);
//获取所有的父分类
const selectAllParent = () =>{
  categoryApi.selectAllParent()
      .then(resp => {
        allParent.value = resp.data;
      })
}
// 被添加商品变量
const goodsAdd = ref({
  name: "",
  dscp: "",
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: "",
  version: "",
  count: null,
  recom: null,
  categoryId: null,
  status: null,
  picList:[]
})
//是否显示添加对话框
const addDislogShow = ref(false);
//新增显示对话框的
const showAddModel = ()=>{
  addDislogShow.value=true;
}
const insert = () =>{
  //处理图片
  for (let i = 0; i < goodsAdd.value.picList.length; i++) {
    goodsAdd.value.picList[i].url = goodsAdd.value.picList[i].realName;
  }
  goodsApi.insert(goodsAdd.value)
      .then(resp => {
        if (resp.code == 10000){
          ElMessage.success(resp.msg);
          selectByPage(1)
          addDislogShow.value=false;
          goodsAdd.value = {
            name: "",
            dscp: "",
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: "",
            version: "",
            count: null,
            recom: null,
            categoryId: null,
            status: null,
            picList: []
          }
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
//根据id 删除商品
const deleteGoods = (id)=>{
  goodsApi.delete(id)
      .then(resp =>{
        if (resp.code == 10000){
          ElMessage.success(resp.msg);
          selectByPage(1)
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
//是否显示修改对话框
const updateDislogShow = ref(false);
//是否显示商品详情对话框
const detailDislogShow = ref(false);
//修改分类变量
const goodsUpdate = ref({
  id: 0,
  name: "",
  dscp: "",
  detail: "",
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: "",
  version: "",
  count: null,
  recom: null,
  categoryId: null,
  status: null,
  picList: []
})
//修改显示对话框的
const showUpdateModel = (id)=>{
  goodsApi.selectById(id)
      .then(resp => {
        goodsUpdate.value = resp.data;
        //处理图片
        for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
          //保存图片真实的名字
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;
        }
        updateDislogShow.value=true;
      })

}
//修改商品分类
const update = ()=>{
  //处理图片
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000){
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum)
          updateDislogShow.value=false;
          goodsUpdate.value = {
            id: 0,
            name: "",
            dscp: "",
            detail: "",
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: "",
            version: "",
            count: null,
            recom: null,
            categoryId: null,
            status: null,
            picList: []
          }
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
//图片上传的钩子函数
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 10000) {
    ElMessage.success(response.msg);
    uploadFile.url = `${SERVER_ADDR.value}/goods/pic/${response.data}`;
    uploadFile.realName = response.data;
  }else {
    ElMessage.error(response.msg);
  }
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只能上传jpg格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}
selectAllParent();
selectByPage(1)
</script>

<style scoped>

</style>